package com.koc.robot.util;

//import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.res.AssetFileDescriptor;

import com.koc.robot.Global;

public class FileHandle 
{
	protected String fileName;
	
	protected FileHandle()
	{
	}
	
	public FileHandle(String fileName)
	{
		this.fileName = fileName;
	}
	
	public byte[] readBytes() throws Exception
	{
		// get the file length
		InputStream input = null;
		
		try
		{
			input = Global.context.getAssets().open(fileName);
		}
		catch (Exception ex)
		{
			throw ex;
		}
		
		int length = input.available();
		
		byte[] buffer = new byte[length];
		int position = 0;
		try
		{
			while (true)
			{
				int count = input.read(buffer, position, buffer.length - position);
				if (count == -1) break;
				position += count;
				if (position == buffer.length)
				{
					// Grow buffer.
					byte[] newBuffer = new byte[buffer.length * 2];
					System.arraycopy(buffer, 0, newBuffer, 0, position);
					buffer = newBuffer;
				}
			}
		}
		catch (IOException ex)
		{
			throw ex;
		}
		finally
		{
			try
			{
				if (input != null) input.close();
			}
			catch (IOException ignored)
			{
			}
		}
		if (position < buffer.length)
		{
			byte[] newBuffer = new byte[position];
			System.arraycopy(buffer, 0, newBuffer, 0, position);
			buffer = newBuffer;
		}
		
		return buffer;
	}
}
